package com.starsea.book.ui.newpage

import android.os.Bundle
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.ActivityVipBinding
import com.starsea.book.ui.newpage.adapter.VipRightAdapter
import com.starsea.book.ui.newpage.adapter.VipTcAdapter
import com.starsea.book.ui.newpage.utils.loadNormalImage
import com.starsea.book.ui.newpage.viewmodel.UserViewModel
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import org.json.JSONObject


/**
 * @author Lee
 * @createTime 2024-01-15 13 GMT+8
 * @desc :
 */
class VipActivity : VMBaseActivity<ActivityVipBinding, UserViewModel>() {
    override val binding by viewBinding(ActivityVipBinding::inflate)
    override val viewModel by viewModels<UserViewModel>()

    lateinit var mAdapter: VipTcAdapter
    lateinit var mAdapterRight: VipRightAdapter

    var thaliId = ""

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        viewModel.setVipHint(binding.tvHint, this)


        mAdapterRight = VipRightAdapter(this)
        binding.rvVipRight.layoutManager = GridLayoutManager(this, 4)
        binding.rvVipRight.adapter = mAdapterRight


        mAdapter = VipTcAdapter(this) {
            thaliId = it.thaliId ?: ""
            binding.rtvConfim.text = "¥${it.price} 确认协议立即开通"
        }
        binding.rvVipTc.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding.rvVipTc.adapter = mAdapter

        viewModel.getVipTcList()
        viewModel.getVipRight()
        viewModel.getUserProfile()

        binding.rtvConfim.setOnClickListener {
            if (TextUtils.isEmpty(thaliId)) {
                toastOnUi("请选择要开通的套餐")
                return@setOnClickListener
            }
            if (!binding.rcbDeal.isSelected) {
                ToastUtils.showShort("请勾选同意特权服务协议")
                return@setOnClickListener
            }


            viewModel.buyVip(thaliId, 2) { resultJson ->
                try {
                    val json = JSONObject(resultJson)
                    val payRunnable: Runnable = Runnable {
                        val alipay = PayTask(this)
                        val result =
                            alipay.payV2(json.getJSONObject("data").getString("payData"), true)
                        toastOnUi(result["memo"].toString())
                        if (result["resultCode"] == "9000") {
                            viewModel.getUserProfile()
                        }
                    }
                    // 必须异步调用
                    val payThread = Thread(payRunnable)
                    payThread.start()
                } catch (e: Exception) {
                    toastOnUi(e.localizedMessage)
                }
            }
        }

        viewModel.vipRightResult.observe(this) {
            mAdapterRight.setItems(it)
        }


        viewModel.vipTcListResult.observe(this) {
            if (it.status == 200) {
                mAdapter.setItems(it.data)
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }

        viewModel.userProfileResult.observe(this) {
            if (it.status == 200) {
                binding.ivHeader.loadNormalImage(this, it.data?.headUrl ?: "")
                binding.tvNickName.text = it.data?.custName ?: ""
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }

        binding.rcbDeal.setOnClickListener {
            binding.rcbDeal.isSelected = !binding.rcbDeal.isSelected
        }
        binding.rcbDeal.movementMethod = LinkMovementMethod.getInstance()
        binding.rcbDeal.text = SpanUtils().append("我已阅读并同意")
            .append("《特权服务协议》")
            .setClickSpan(
                ContextCompat.getColor(
                    this,
                    R.color.color_2661F7
                ), false
            ) {
                startActivity<PrivateDealActivity> {
                    putExtra("type", "MEMBER")
                }
            }
            .append("的全部内容")
            .create()

    }


}